package com.tianji.promotion.utils;

import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RLock;
import org.springframework.stereotype.Component;

@Aspect
@Component
@RequiredArgsConstructor
public class MyLockAsspect {
    private final MyLockType myLockType;
    private final MyLockFacory myLockFacory;

    @Around("@annotation(myLock)")
    public Object tryLock(ProceedingJoinPoint pjp, MyLock myLock) throws Throwable {
        //1.获取锁对象
        RLock lock = myLockFacory.getLock(myLockType, myLock.name());
        //2注册锁   注册锁失败的策略
        //boolean isLock = lock.tryLock();
        boolean isLock = myLock.lockStrategy().tryLock(lock, myLock);
        //3.失败抛异常
        if (!isLock) {
            return null;
        }
        try {
            //3.成功执行业务代码
            return pjp.proceed();
        } finally {
            //4.释放锁
            lock.unlock();
        }
    }

}
